package com.cfswt.tasksystem.controller;

import com.cfswt.tasksystem.mapper.UserMapper;
import com.cfswt.tasksystem.pojo.dto.UserLoginDTO;
import com.cfswt.tasksystem.pojo.dto.UserRegDTO;
import com.cfswt.tasksystem.pojo.dto.UserUpdateDTO;
import com.cfswt.tasksystem.pojo.entity.User;
import com.cfswt.tasksystem.pojo.vo.UserAdminVO;
import com.cfswt.tasksystem.pojo.vo.UserVO;
import com.cfswt.tasksystem.response.JsonResult;
import com.cfswt.tasksystem.response.StatusCode;
import com.cfswt.tasksystem.security.CustomRememberMeServices;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired(required = false)
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;


    @PostMapping("/register")
    public JsonResult doRegister(@RequestBody UserRegDTO userRegDTO) {
        UserVO userVO = userMapper.selectUserByName(userRegDTO.getUserName());
        if (userVO != null) {
            return new JsonResult(StatusCode.USERNAME_ALREADY_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        user.setCreateTime(new Date());
        String encode = passwordEncoder.encode(userRegDTO.getPassword());
        user.setPassword(encode);
        userMapper.insertUser(user);
        return JsonResult.ok();
    }

    //注入认证管理器
    @Autowired
    private AuthenticationManager manager;

    @Autowired
    private CustomRememberMeServices rememberMeServices;

    @PostMapping("/login")
    public JsonResult doLogin(@RequestBody UserLoginDTO userLoginDTO, HttpServletRequest request, HttpServletResponse response) {
        System.out.println(userLoginDTO);
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                userLoginDTO.getUserName(),
                userLoginDTO.getPassword()
        );
        Authentication authenticate = manager.authenticate(authRequest);
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        System.out.println(authenticate);

        // 处理 Remember Me 功能
        if (userLoginDTO.isRememberMe()) {
            System.out.println("Processing RememberMe...");
            try {
                // 使用自定义的 loginSuccess 方法
                ((CustomRememberMeServices) rememberMeServices).loginSuccess(request, response, authenticate, true);
                System.out.println("RememberMe processed successfully.");
            } catch (Exception e) {
                System.out.println("RememberMe failed: " + e.getMessage());
                e.printStackTrace();
            }
        }

        Map<String, Object> data = new HashMap<>();
        data.put("user", authenticate.getPrincipal());
        return JsonResult.ok(data);
    }


    @GetMapping("/logout")
    public JsonResult doLogout() {
        SecurityContextHolder.clearContext();
        return JsonResult.ok();
    }

    @PostMapping("/update")
    public JsonResult doUpdate(@RequestBody UserUpdateDTO userUpdateDTO) {
        if (userUpdateDTO.getAvatar() != null) {
            String imgUrl = userMapper.selectAvatarById(userUpdateDTO.getId());
            new File("e:/appFile" + imgUrl).delete();
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateDTO, user);
        userMapper.updateUser(user);
        return JsonResult.ok();
    }

    @GetMapping("")
    public JsonResult selectUserAdmin() {
        List<UserAdminVO> userAdminVOS = userMapper.selectUserAdminVO();
        return JsonResult.ok(userAdminVOS);
    }

    @DeleteMapping("/{id}/delete")
    public JsonResult delete(@PathVariable int id) {
        userMapper.deletUserById(id);
        return JsonResult.ok();
    }

    @PostMapping("/modify/password")
    public JsonResult modifyPassword(@RequestParam String oldPassword,
                                     @RequestParam String newPassword) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String name = authentication.getName();
        String currentPassword = userMapper.selectPasswordByuserName(name);
        if (passwordEncoder.matches(oldPassword, currentPassword)) {
            String encode = passwordEncoder.encode(newPassword);
            userMapper.modifyPassword(name, encode);
            return JsonResult.ok();
        }
        return JsonResult.ok(StatusCode.PASSWORD_ERROR);
    }
}

